<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>红绿灯倒计时</title>
		<link rel="stylesheet" href="red.css" />
	</head>
	<body>
		<div class="box">
			<!--红灯-->
			<div id="r"></div>
			<!--黄灯-->
			<div id="y"></div>
			<!--绿灯-->
			<div id="g"></div>
			<!--倒计时-->
			<div id="count" class="count"></div>
		</div>
		<script>
			/* 1、设置红黄绿灯、倒计时对象
			   2、静态：设置绿灯亮时初始化页面
			   3、动态：实现红绿灯倒计时：计时器*/
		var lamp={
				 //红灯相关数据
			red: {	
				obj:document.getElementById('r'),
				time:30,
				style:['red','gainsboro','gainsboro'],
				next:'green'
			},
			     //黄灯相关数据
			yellow:{
				obj:document.getElementById('y'),
			   time:5,
			   style:['gainsboro','yellow','gainsboro'],
			   next:'red'
			},
                 //绿灯相关数据
            green:{
				obj:document.getElementById('g'),
				time:35,
				style:['gainsboro','gainsboro','green'],
				next:'yellow'
			},
			change:function(style){
				this.red.obj.style.background=style[0];
				this.yellow.obj.style.background=style[1];
                this.green.obj.style.background=style[2];
			}
		   } ;
		    //创建倒计时对象：显示倒计时（两位数）
		    var count={
		    	obj:document.getElementById('count'),
		    	change:function(num){
		    		this.obj.innerHTML=(num<10?'0'+num:num);
		    	}
		    };
		    //2、静态：设置绿灯亮时初始化页面
		    //1)获取当前绿灯的相关数据2.设置剩余时间3.设置背景颜色
		    var now =lamp.green;
		    var t=now.time;
		    count.change(now.time);
		    lamp.change(now.style);
		    //3.动态：实现红绿灯倒计时：计时器
		    setInterval(myfun,1000);
		    function myfun(){
		    	/*时间计数--若<=0：当前灯数据，更改样式
		    	 更改时间
		    	 */
		    	if(t--<=0){
		    		now=lamp[now.next];
		    		t=now.time;
		    		lamp.change(now.style);
		    	}
		    	count.change(t);
		    }
		</script>		
	</body>
</html>
